package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/myblogs/controllers"
	"github.com/myblogs/dao/mysql"
	"github.com/myblogs/logger"
	"github.com/myblogs/routers"
	"github.com/myblogs/settings"
	"go.uber.org/zap"
	_ "net/http/pprof"
)

func main() {

	go func() {
		http.ListenAndServe("localhost:6060", nil)
	}()
	// go install github.com/air-verse/air@latest
	// 初始化settings
	if err := settings.Init(); err != nil {
		panic(err)
	}
	// 初始化logger
	logCfg := &settings.Config.LogConfig
	if err := logger.InitLogger(logCfg, settings.Config.Mode); err != nil {

		fmt.Printf("init logger failed, err:%v\n", err)
		return
	}

	if err := controllers.InitTrans("zh"); err != nil {
		zap.S().Error("初始化翻译失败", zap.Error(err))
	}

	// 初始化mysql
	if err := mysql.Init(); err != nil {
		zap.S().Error("mysql 初始化错误", zap.Error(err))
	}
	// 初始化路由
	route := routers.NewRouter()
	route.RegisterRouter()

	srv := &http.Server{
		Addr:    ":" + settings.Config.Port,
		Handler: route.GetEngine(),
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil {
			zap.S().Error("http 服务启动失败", zap.Error(err))
		}
	}()

	gin.SetMode(gin.DebugMode)

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	zap.S().Info("服务启动成功,监听端口:%s", settings.Config.Port)
	<-quit
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		zap.S().Error("http 服务关闭失败", zap.Error(err))
	}
	// 关闭数据库连接
	if err := mysql.Close(); err != nil {
		zap.S().Error("mysql 关闭错误", zap.Error(err))
	}
	zap.S().Info("服务关闭成功")

}
